<?php
/**
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     pmvc_formSelect
 * Purpose:  renders a select box
 * -------------------------------------------------------------
 */

use pmvc\template\smarty\SmartyUtil;

function smarty_function_pmvc_formSelect(array $params, &$smarty) {

	// get selected options
	$selectedOptions = SmartyUtil::getSelectedOptions($params, $smarty);
	unset($params["selectedOptions"]);

	// id=
	if (!isset($params["id"])
		&& isset($params["name"])) {
		$params["id"] = $params["name"];
	}

	// get the options
	$options = Array();
	if (isset($params["options"])) {
		$options = $params["options"];
		unset($params["options"]);
	}

	// get the id for the options
	$id = "optionval_";
	if (isset($params["id"])) {
		$id = $params["id"];
	} else if (isset($params["name"])) {
		$id = $params["name"];
	}

	// build the select
	$ret = '<select '.SmartyUtil::renderParamsAsAttributes($params, $smarty).'>';
	foreach ($options as $val => $text) {
		$ret .= '<option id="'.htmlspecialchars($id.'_'.$val).'"';
		if (isset($selectedOptions) && array_search($val, $selectedOptions)!==false) {
			$ret .= ' selected="selected"';
		}
		$ret .= ' value="'.htmlspecialchars($val).'">'.$text.'</option>';
	}
	$ret .= '</select>';

	// return the select
    return SmartyUtil::returnOrAssign($smarty, $params, $ret);
}

?>